<?php

/**
 * DoctrineTemplateVersionable
 *
 * @package     flexiwik
 * @subpackage  template
 */
class DoctrineTemplateVersionable extends Doctrine_Template
{
  public function setTableDefinition()
  {
    $this->addListener(new DoctrineTemplateListenerVersionable);
  }
  
  public function getLastRevision()
  {
    $revision = kcDoctrineQuery::create()
                ->from('Revision r')
                ->where('r.page_id = ?', $this->getInvoker()->getId())
                ->orderBy('r.id DESC')
                ->fetchOne();
                
    return $revision;
  }
  
  public function getRevisionFromVersion($version)
  {
    $revision = kcDoctrineQuery::create()
                ->from('Revision r')
                ->where('r.page_id = ?', $this->getInvoker()->getId())
                ->andWhere('r.version = ?', $version)
                ->fetchOne();
                
    return $revision; 
  }
  
  public function getMaxVersion()
  {
    $revision = kcDoctrineQuery::create()
                ->select('IFNULL(MAX(r.version), 0) as max_version')
                ->from('Revision r')
                ->where('r.page_id = ?', $this->getInvoker()->getId())
                ->fetchOne();
                
    $max_version = $revision->getMaxVersion();
    return $max_version;
  }
  
  public function revert($version)
  {
    $revision = $this->getRevisionFromVersion($version);
    
    if (!$revision->getId())
    {
      throw new Doctrine_Record_Exception('Version ' . $version . ' does not exist!');
    }
    $text = $revision->getText();
    
    $newRevision = $this->copyObject($revision, array('created_at', 'updated_at'));
    $newText     = $this->copyObject($text, array('created_at', 'updated_at'));
    
    $newRevision->unsetModifieds(array('created_at', 'updated_at'));
    $newText->unsetModifieds(array('created_at', 'updated_at'));
    
    $newRevision->setUserId(sfContext::getInstance()->getUser()->getUserId());
    $newRevision->setRevisionId($revision->getId());
    $newRevision->setText($newText);
    $newRevision->setVersion($this->getInvoker()->getLastRevision()->getVersion() + 1);
    
    $this->getInvoker()->setLength($revision->getLength());
    $this->getInvoker()->addRevision($newRevision);
  }
  
  protected function copyObject(kcDoctrineRecord $object, $fields = array())
  {
    $object->unsetModifieds($fields, true);
    $newObject = $object->copy();
    $newObject->unsetModifieds($fields);
    
    return $newObject;
  }
}